import { useBoolean } from '@gnlab/utils/env-react'
import { Tag } from 'antd'
import type { BaseAccount } from '@/services/auth'
import { getAccountsData } from '../hooks'
import type { ChoosingProps, AccountsData } from '../hooks'
import './index.less'
import { ChooseAccountModal } from '../modal'

interface SingleOnChange {
  (id: string, account: BaseAccount): void
  (id: null, account: null): void
}
type MultiOnChange = (id: string[], account: BaseAccount[]) => void

export function ChooseAccountInput(
  props: Pick<ChoosingProps, 'lockChoosed' | 'disabled'> &
    (
      | { multiple?: false; value?: string | null; onChange?: SingleOnChange }
      | { multiple: true; value?: string[]; onChange?: MultiOnChange }
    ),
) {
  const {
    multiple = false,
    value: rawValue,
    onChange: rawOnChange = () => {},
    ...choosingProps
  } = props

  const [accountsData, setAccountsData] = useState<AccountsData | null>(null)
  useEffect(() => {
    let cancelled = false
    void getAccountsData().then(data => {
      if (cancelled) return
      setAccountsData(data)
    })
    return () => {
      cancelled = true
    }
  }, [])

  // 整理 value 和 onChange
  const valueIds = multiple
    ? ((rawValue ?? []) as string[])
    : typeof rawValue === 'string'
    ? [rawValue]
    : []

  const value = valueIds.map(
    id => accountsData?.map.get(id) ?? { id, name: `ID:${id}`, avatar: '', remark: '' },
  )

  function onChange(choosed: BaseAccount[]) {
    if (multiple)
      (rawOnChange as MultiOnChange)(
        choosed.map(v => v.id),
        choosed,
      )
    else if (choosed.length) (rawOnChange as SingleOnChange)(choosed[0]!.id, choosed[0]!)
    else (rawOnChange as SingleOnChange)(null, null)
  }

  function remove(id: string) {
    onChange(value.filter(v => v.id !== id))
  }

  const [choosing, startChoose, finishChoose] = useBoolean(false)
  const handleChoosed = (value: BaseAccount[]) => {
    finishChoose()
    onChange(value)
  }

  if (!accountsData) return null

  return <>
    <div className="qun-choose-account-input" onClick={startChoose}>
      {value.length ? (
        <div className="qun-choosed">
          {value.map(account => <Tag key={account.id} closable onClose={() => remove(account.id)}>
            {account.name}
          </Tag>)}
        </div>
      ) : (
        <div className="qun-placeholder">请选择账号</div>
      )}
    </div>

    <ChooseAccountModal
      {...choosingProps}
      visible={choosing}
      multiple={multiple}
      initialChoosed={value.map(v => v.id)}
      onChoosed={handleChoosed}
      onCancel={finishChoose}
    />
  </>
}
